package dao

import (
	"fmt"
	"log"
	"main/model"
	"main/tool"
)

type MemberDao struct {
	*tool.OrmEngine
}

func (md *MemberDao) QueryUserById(id int64) *model.Member {
	var member model.Member
	if _, err := md.Where("id = ?", id).Get(&member); err != nil {
		return nil
	}
	return &member
}

// QueryByLogin 通过用户名和密码查询
func (md *MemberDao) QueryByLogin(name string, password string) *model.Member {
	var member model.Member
	_, err := md.Where(" user_name = ? and password = ?", name, password).Get(&member)
	if err != nil {
		log.Printf("query by login failed: %v", err)
		return nil
	}
	return &member
}

func (md *MemberDao) InsertMember(member model.Member) int64 {
	id, err := md.InsertOne(&member)
	if err != nil {
		log.Printf("会员插入失败: %s\n", err.Error())
		return 0
	}
	return id
}

func (md *MemberDao) QueryByPhone(phone string) *model.Member {
	var member model.Member
	if _, err := md.Where(" mobile = ? ", phone).Get(&member); err != nil {
		log.Printf("query failed: %v", err)
	}
	return &member
}

// ValidateSmsCode 验证手机号和验证码在sms_code表中是否存在
func (md *MemberDao) ValidateSmsCode(phone string, code string) *model.SmsCode {
	var sms model.SmsCode
	if _, err := md.Where("phone = ? and code = ?", phone, code).Get(&sms); err != nil {
		fmt.Println(err.Error())
	}
	return &sms
}

func (md *MemberDao) InsertCode(sms model.SmsCode) int64 {
	result, err := md.InsertOne(&sms)
	if err != nil {
		log.Printf("Error inserting, %s\n", err.Error())
	}
	return result
}

func (md *MemberDao) UploadMemberAvatar(id int64, fileName string) int64 {
	member := &model.Member{
		Avatar: fileName,
	}
	uid, err := md.Where("id = ?", id).Update(&member)
	if err != nil {
		log.Printf("Error updating, %s\n", err.Error())
		return 0
	}
	return uid
}




